package com.tuxing.draa_data.service.subject;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.tuxing.draa_data.dao.center.NewDcBibliographyPeriDao;
import com.tuxing.draa_data.dao.subject.*;
import com.tuxing.draa_data.dto.EjEIJournalExcelDto;
import com.tuxing.draa_data.dto.EjJcrJournalExcelDto;
import com.tuxing.draa_data.dto.EsiJournalExcelDto;
import com.tuxing.draa_data.en.SubjectTypeEnum;
import com.tuxing.draa_data.pojo.center.NewDcBibliographyPeri;
import com.tuxing.draa_data.pojo.subject.*;
import com.tuxing.draa_data.util.ConvertUtil;
import com.tuxing.draa_data.util.FormatUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author yuanshihang
 * @version 1.0
 * @className SubjectServiceImpl
 * @description 基础描述:学科和核心数据处理
 * @date 2021/12/15 15:55
 */
@Service
@Slf4j
public class SubjectServiceImpl implements SubjectService {

    @Resource
    private NewDcSubjectDictDao newDcSubjectDictDao;

    @Resource
    private NewDcWosSubAttrDao newDcWosSubAttrDao;

    @Resource
    private YshWosExcelDataDao yshWosExcelDataDao;

    @Resource
    private NewDcBibliographyPeriDao newDcBibliographyPeriDao;

    @Resource
    private YshScoupsJournalDataDao yshScoupsJournalDataDao;

    @Resource
    private NewDcScoupsSubAttrDao newDcScoupsSubAttrDao;

    @Resource
    private NewDcEsiSubAttrDao newDcEsiSubAttrDao;

    @Override
    public void wosData() {
        int pageNum = 1;
        while (true) {
            Page<YshWosExcelData> page = new Page<>(pageNum, 1000);
            List<YshWosExcelData> wosExcelList = yshWosExcelDataDao.findListByPage(page);
            if (!CollectionUtils.isEmpty(wosExcelList)) {
                for (YshWosExcelData yshWosExcelData : wosExcelList) {
                    String subjects = yshWosExcelData.getSubjects();
                    String[] subjectArray = subjects.split("\\|");

                    NewDcBibliographyPeri newDcBibliographyPeri = saveAndCheckWosJournal(yshWosExcelData);
                    Long recordId = newDcBibliographyPeri.getRecordId();

                    for (String subjectName : subjectArray) {
                        subjectName = subjectName.trim();
                        //匹配学科数据
                        Long subId = newDcSubjectDictDao.findSubIdByWosTypeSubName(yshWosExcelData.getType(), subjectName);
                        if (subId == null || subId == 0L) {
                            NewDcSubjectDict newDcSubjectDict = new NewDcSubjectDict();
                            newDcSubjectDict.createByWos(ConvertUtil.objToLong(yshWosExcelData.getType()), subjectName);
                            newDcSubjectDictDao.insert(newDcSubjectDict);
                            subId = newDcSubjectDict.getSubId();
                        }

                        //学科信息保存
                        Integer count = newDcWosSubAttrDao.findCountByRecordIdSubIdYear(recordId, subId, 2021);
                        if (count == null || count == 0) {
                            NewDcWosSubAttr dcWosSubAttr = new NewDcWosSubAttr();
                            dcWosSubAttr.create(recordId, subId, 2021, null);
                            newDcWosSubAttrDao.insert(dcWosSubAttr);
                        }
                    }
                }
            }
            if (!page.hasNext()) {
                break;
            } else {
                pageNum++;
            }
        }
    }

    /**
     * @return 暂无返回结果
     * @decpription scoups核心期刊数据解析
     * @author yuanshihang
     * @date 2021/12/27 14:25
     * @version 1.0
     */
    @Override
    public void scoupsJournalDataParse() {
        //设置解析scoups核心期刊的年份范围
        List<Integer> yearList = Lists.newArrayList(2017, 2018, 2019, 2020);
        for (Integer year : yearList) {
            List<YshScoupsJournalData> listByYear = yshScoupsJournalDataDao.findListByYear(year);
            if (CollectionUtils.isEmpty(listByYear)) {
                continue;
            }
            for (YshScoupsJournalData yshScoupsJournalData : listByYear) {
                NewDcBibliographyPeri peri = checkAndSaveScoupsJournal(yshScoupsJournalData);
                if (peri == null) {
                    continue;
                }
                Integer count = newDcScoupsSubAttrDao.findCountByRecordIdYear(peri.getRecordId(), year);
                if (count != null && count > 0) {
                    continue;
                }
                NewDcScoupsSubAttr scoupsSubAttr = new NewDcScoupsSubAttr();
                scoupsSubAttr.setRecordId(peri.getRecordId());
                scoupsSubAttr.setYear(year);
                scoupsSubAttr.setCiteScore(yshScoupsJournalData.getCiteScore());
                scoupsSubAttr.setSjr(yshScoupsJournalData.getSjr());
                scoupsSubAttr.setSnip(yshScoupsJournalData.getSnip());

                scoupsSubAttr.setCreatedBy(-1);
                scoupsSubAttr.setCreatedTime(LocalDateTime.now());
                scoupsSubAttr.setUpdatedBy(-1);
                scoupsSubAttr.setUpdatedTime(LocalDateTime.now());

                newDcScoupsSubAttrDao.insert(scoupsSubAttr);
            }
        }
    }

    /**
     * @param excelList esi的表格数据
     * @return 暂无返回结果
     * @decpription 进行esi核心学科数据保存
     * @author yuanshihang
     * @date 2021/12/29 10:09
     * @version 1.0
     */
    @Override
    public void esiJournalParse(List<EsiJournalExcelDto> excelList) {

        if (CollectionUtils.isNotEmpty(excelList)) {
            log.info("读取到Excel表格数据：" + excelList.size() + "条，比对解析开始");
            for (EsiJournalExcelDto esiJournalExcelDto : excelList) {
                try {
                    //获取期刊名和标准号进行期刊比对
                    String journalName = esiJournalExcelDto.getJournalName();
                    String printIssn = FormatUtil.formatISSN(esiJournalExcelDto.getP_issn());
                    String onlineIssn = FormatUtil.formatISSN(esiJournalExcelDto.getE_issn());
                    Long recordId = checkJournal(journalName, printIssn, onlineIssn);
                    if (recordId == null) {
                        log.info("esi期刊暂未与基准期刊比对上，esi期刊信息：" + JSON.toJSONString(esiJournalExcelDto));
                        continue;
                    }

                    //获取学科，进行学科比对和保存
                    String subject = esiJournalExcelDto.getSubject();
                    Long subId = newDcSubjectDictDao.findSubIdByTypeSubName(SubjectTypeEnum.ESI.getSubType(), subject);
                    if (subId == null || subId == 0) {
                        NewDcSubjectDict newDcSubjectDict = new NewDcSubjectDict();
                        newDcSubjectDict.create(null, subject, SubjectTypeEnum.ESI.getSubType(), null, subject, 0L);
                        newDcSubjectDictDao.insert(newDcSubjectDict);
                        subId = newDcSubjectDict.getSubId();
                    }

                    //保存对应关系
                    Integer count = newDcEsiSubAttrDao.findCountByRecordIdSubIdYear(recordId, subId, esiJournalExcelDto.getYear());
                    if (count == null || count == 0) {
                        NewDcEsiSubAttr newDcEsiSubAttr = new NewDcEsiSubAttr();
                        newDcEsiSubAttr.create(recordId, subId, esiJournalExcelDto.getYear());
                        newDcEsiSubAttrDao.insert(newDcEsiSubAttr);
                    }
                } catch (Exception ex) {
                    log.error("处理esi期刊数据错误，错误原因：" + ex.getMessage(), ex);
                    log.info("错误数据：" + JSON.toJSONString(esiJournalExcelDto));
                }
            }
        }


    }

    @Resource
    private NewDcEiAttrDao newDcEiAttrDao;

    /**
     * @param excelList ei的表格数据
     * @return 暂无返回数据
     * @decpription EI期刊核心资源数据解析保存
     * @author yuanshihang
     * @date 2022/2/14 10:39
     * @version 1.0
     */
    @Override
    public void eiJournalParse(List<EjEIJournalExcelDto> excelList) {
        if (!CollectionUtils.isEmpty(excelList)) {
            for (EjEIJournalExcelDto ejEIJournalExcelDto : excelList) {
                //分别获取题名，标准号数据
                String journalName = ejEIJournalExcelDto.getJournalName();
                String printIssn = ejEIJournalExcelDto.getPrintIssn();
                String onlineIssn = ejEIJournalExcelDto.getOnlineIssn();
                //和中央标准库进行比较
                Long recordId = checkJournal(journalName, printIssn, onlineIssn);
                //如果没有比对上，进行新增保存
                if (recordId == null) {
                    NewDcBibliographyPeri peri = new NewDcBibliographyPeri();
                    peri.setLangCode(1);
                    peri.setTitle(journalName);
                    peri.setPIssn(printIssn);
                    peri.setOIssn(onlineIssn);
                    peri.setPublisher(ejEIJournalExcelDto.getPublisher());
                    newDcBibliographyPeriDao.insert(peri);
                    log.info("解析数据未和中央数据匹配上，进行新增操作，新增后数据：" + JSON.toJSONString(peri));
                    recordId = peri.getRecordId();
                }
                //核心表数据保存
                int year = 2021;
                Integer countByJidYear = newDcEiAttrDao.findCountByJidYear(recordId, year);
                if (countByJidYear == null || countByJidYear == 0) {
                    NewDcEiAttr newDcEiAttr = new NewDcEiAttr();
                    newDcEiAttr.create(recordId, year);
                    newDcEiAttrDao.insert(newDcEiAttr);
                }
            }
        }
    }

    @Resource
    private NewDcJcrSubAttrDao newDcJcrSubAttrDao;

    private Integer i = 1;

    /**
     * @param excelList ei的表格数据
     * @return 暂无返回数据
     * @decpription EI期刊核心资源数据解析保存
     * @author yuanshihang
     * @date 2022/2/14 10:39
     * @version 1.0
     */
    @Override
    public void jcrJournalParse(List<EjJcrJournalExcelDto> excelList) {
        if (!CollectionUtils.isEmpty(excelList)) {
            for (EjJcrJournalExcelDto ejEIJournalExcelDto : excelList) {

                String jcrSubject = ejEIJournalExcelDto.getJcrSubject();
                if (Strings.isNullOrEmpty(jcrSubject)) {
                    continue;
                }
                //分别获取题名，标准号数据
                String journalName = ejEIJournalExcelDto.getJournalName();
                String printIssn = ejEIJournalExcelDto.getPrintIssn();
                String onlineIssn = ejEIJournalExcelDto.getOnlineIssn();
                //和中央标准库进行比较
                Long recordId = checkJournal(journalName, printIssn, onlineIssn);
                //如果没有比对上，进行新增保存
                if (recordId == null) {
                    NewDcBibliographyPeri peri = new NewDcBibliographyPeri();
                    peri.setLangCode(1);
                    peri.setTitle(journalName);
                    peri.setPIssn(printIssn);
                    peri.setOIssn(onlineIssn);
                    peri.setPublisher(ejEIJournalExcelDto.getPublisher());
                    newDcBibliographyPeriDao.insert(peri);
                    log.info("解析数据未和中央数据匹配上，进行新增操作，新增后数据：" + JSON.toJSONString(peri));
                    recordId = peri.getRecordId();
                }
                Long parentId = 1314834208812560386L;//Social Science
//                Long parentId = 1314830769013518338L;//Science
                Long jcrSubId = newDcSubjectDictDao.findJcrSubIdBySubNameParentId(parentId, jcrSubject);
//                if (recordId == 1468430084747247619L || recordId == 1468430230356705283L || recordId == 1468432950463512580L){
//                    log.info("期刊核心已存在，核心信息：" + JSON.toJSONString(ejEIJournalExcelDto));
//                    log.info("期刊比对结果ID：" + recordId + "，学科ID：" + jcrSubId);
//                }
                Integer count = newDcJcrSubAttrDao.findCountByRecordIdYearSubIdQ(recordId, 2018, jcrSubId, ejEIJournalExcelDto.getJcrQ(), parentId);
                if (count == null || count == 0) {
                    NewDcJcrSubAttr newDcJcrSubAttr = new NewDcJcrSubAttr();
                    newDcJcrSubAttr.create(recordId, jcrSubId, ejEIJournalExcelDto.getJcrQ(), 2018, ejEIJournalExcelDto.getIfValue(), parentId);
                    newDcJcrSubAttrDao.insert(newDcJcrSubAttr);
                } else {
                    log.info("期刊核心已存在，核心信息：" + JSON.toJSONString(ejEIJournalExcelDto));
                    log.info("期刊比对结果ID：" + recordId + "，学科ID：" + jcrSubId);
                }

            }
            log.info(excelList.size() + "条数据批次处理完成");
        }
    }

    /**
     * @param title      期刊名称
     * @param printIssn  printIssn号
     * @param onlineIssn onlineIssn号
     * @return 期刊ID
     * @decpription 进行esi核心期刊比对
     * @author yuanshihang
     * @date 2021/12/29 17:54
     * @version 1.0
     */
    public Long checkJournal(String title, String printIssn, String onlineIssn) {
        if (!Strings.isNullOrEmpty(printIssn)) {
            NewDcBibliographyPeri oneByPISSN = newDcBibliographyPeriDao.findOneByPISSN(printIssn, 1);
            if (oneByPISSN != null) {
                return oneByPISSN.getRecordId();
            }
        }

        if (!Strings.isNullOrEmpty(onlineIssn)) {
            NewDcBibliographyPeri oneByEISSN = newDcBibliographyPeriDao.findOneByEISSN(onlineIssn);
            if (oneByEISSN != null) {
                return oneByEISSN.getRecordId();
            } else {
                NewDcBibliographyPeri oneByTitle = newDcBibliographyPeriDao.findOneByTitle(title);
                if (oneByTitle != null) {
                    return oneByTitle.getRecordId();
                } else {
                    return null;
                }
            }
        } else {
            NewDcBibliographyPeri oneByTitle = newDcBibliographyPeriDao.findOneByTitle(title);
            if (oneByTitle != null) {
                return oneByTitle.getRecordId();
            } else {
                return null;
            }
        }
    }

    /**
     * @param yshWosExcelData wos的临时数据
     * @return 匹配得到的中心数据
     * @decpription 进行wos的期刊数据匹配和保存
     * @author yuanshihang
     * @date 2021/12/16 19:54
     * @version 1.0
     */
    private NewDcBibliographyPeri saveAndCheckWosJournal(YshWosExcelData yshWosExcelData) {
        String printIssn = yshWosExcelData.getPIssn();
        String onlineIssn = yshWosExcelData.getEIssn();
        if (!Strings.isNullOrEmpty(printIssn)) {
            NewDcBibliographyPeri oneByPISSN = newDcBibliographyPeriDao.findOneByPISSN(printIssn, 1);
            if (oneByPISSN != null) {
                return oneByPISSN;
            }
        }

        if (!Strings.isNullOrEmpty(onlineIssn)) {
            NewDcBibliographyPeri oneByEISSN = newDcBibliographyPeriDao.findOneByEISSN(onlineIssn);
            if (oneByEISSN != null) {
                return oneByEISSN;
            } else {
                NewDcBibliographyPeri oneByTitle = newDcBibliographyPeriDao.findOneByTitle(yshWosExcelData.getTitle());
                if (oneByTitle != null) {
                    return oneByTitle;
                } else {
                    return saveJournal(yshWosExcelData);
                }
            }
        } else {
            NewDcBibliographyPeri oneByTitle = newDcBibliographyPeriDao.findOneByTitle(yshWosExcelData.getTitle());
            if (oneByTitle != null) {
                return oneByTitle;
            } else {
                return saveJournal(yshWosExcelData);
            }
        }
    }

    /**
     * @param yshWosExcelData wos期刊数据
     * @return 保存结果
     * @decpription 保存期刊数据
     * @author yuanshihang
     * @date 2021/12/16 19:59
     * @version 1.0
     */
    private NewDcBibliographyPeri saveJournal(YshWosExcelData yshWosExcelData) {
        NewDcBibliographyPeri journal = new NewDcBibliographyPeri();
        journal.createByWos(yshWosExcelData);
        newDcBibliographyPeriDao.insert(journal);
        return journal;
    }

    /**
     * @param yshScoupsJournalData 临时的scoups期刊核心数据
     * @return 期刊信息
     * @decpription 进行scoups期刊核心比对和更新保存
     * @author yuanshihang
     * @date 2021/12/27 15:34
     * @version 1.0
     */
    private NewDcBibliographyPeri checkAndSaveScoupsJournal(YshScoupsJournalData yshScoupsJournalData) {
        String title = yshScoupsJournalData.getTitle();
        String printIssn = yshScoupsJournalData.getPrintIssn();
        String eIssn = yshScoupsJournalData.getEIssn();
        //对ISSN号进行标准化处理，并进行返填
        printIssn = FormatUtil.formatISSN(printIssn);
        eIssn = FormatUtil.formatISSN(eIssn);

        //回填
        yshScoupsJournalData.setPrintIssn(printIssn);
        yshScoupsJournalData.setEIssn(eIssn);

        if (!Strings.isNullOrEmpty(printIssn)) {
            NewDcBibliographyPeri oneByPISSN = newDcBibliographyPeriDao.findOneByPISSN(printIssn, 1);
            if (oneByPISSN != null) {
                return oneByPISSN;
            }
        }

        if (!Strings.isNullOrEmpty(eIssn)) {
            NewDcBibliographyPeri oneByEISSN = newDcBibliographyPeriDao.findOneByEISSN(eIssn);
            if (oneByEISSN != null) {
                return oneByEISSN;
            } else {
                NewDcBibliographyPeri oneByTitle = newDcBibliographyPeriDao.findOneByTitle(title);
                if (oneByTitle != null) {
                    return oneByTitle;
                } else {
                    return saveOneJournal(yshScoupsJournalData);
                }
            }
        } else {
            NewDcBibliographyPeri oneByTitle = newDcBibliographyPeriDao.findOneByTitle(title);
            if (oneByTitle != null) {
                return oneByTitle;
            } else {
                return saveOneJournal(yshScoupsJournalData);
            }
        }

//        return null;
    }

    /**
     * //     * @param peri          标准期刊信息
     *
     * @param scoupsJournal scoups期刊信息
     * @return 新增的标准期刊信息
     * @decpription 通过scoups期刊信息生成新的标准期刊信息
     * @author yuanshihang
     * @date 2021/12/28 9:46
     * @version 1.0
     */
    private NewDcBibliographyPeri saveOneJournal(YshScoupsJournalData scoupsJournal) {
        try {
            NewDcBibliographyPeri peri = new NewDcBibliographyPeri();
            peri.createByScoups(scoupsJournal);
            newDcBibliographyPeriDao.insert(peri);
            String periJsonString = JSON.toJSONString(peri);
            log.info("新增标准化期刊信息（scoups），期刊信息：" + periJsonString);
            return peri;
        } catch (Exception ex) {
            log.error("新增标准化期刊信息错误，错误原因：" + ex.getMessage(), ex);
        }
        return null;
    }

    /**
     * @param title     题名
     * @param printIssn 标准号
     * @param cn        中文期刊CN号
     * @return 期刊ID
     * @descpription 查询中文期刊
     * @author yuanshihang
     * @date 2022/2/17 11:16
     * @Version 1.0
     */
    public Long checkCnJournal(String title, String printIssn, String cn) {
        if (!Strings.isNullOrEmpty(printIssn)) {
            NewDcBibliographyPeri oneByPISSN = newDcBibliographyPeriDao.findOneByPISSN(printIssn, 3);
            if (oneByPISSN != null) {
                return oneByPISSN.getRecordId();
            }
        }

        if (!Strings.isNullOrEmpty(cn)) {
            NewDcBibliographyPeri oneByEISSN = newDcBibliographyPeriDao.findOneByCN(cn);
            if (oneByEISSN != null) {
                return oneByEISSN.getRecordId();
            } else {
                NewDcBibliographyPeri oneByTitle = newDcBibliographyPeriDao.findOneByTitle(title);
                if (oneByTitle != null) {
                    return oneByTitle.getRecordId();
                } else {
                    return null;
                }
            }
        } else {
            NewDcBibliographyPeri oneByTitle = newDcBibliographyPeriDao.findOneByTitle(title);
            if (oneByTitle != null) {
                return oneByTitle.getRecordId();
            } else {
                return null;
            }
        }
    }
}
